package edu.lnu.project.timeeditapp.activites;

import java.util.ArrayList;
import java.util.Calendar;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.SparseArray;

import edu.lnu.project.timeeditapp.db.TimeEditDataSource;
import edu.lnu.project.timeeditapp.db.TimeEditDbHelper;
import edu.lnu.project.timeeditapp.helper.MyHelper;
import edu.lnu.project.timeeditapp.parser.Event;

public class ReminderService extends Service {

	private Context mContext;
	TimeEditDataSource datasource;
	Thread thread;
	Thread clockThread;
	public static SparseArray<Event> allEvents;
	static ArrayList<Integer> allEventsIndices;

	//Variables to be used when the alarms are compared with current time in the for loop in IsItTime()
	int compareHour = 0;
	int compareMinute = 0;

	int currentHour = 0;
	int currentMinute = 0;

	public SharedPreferences visibilityColorPreferences;
	public  SharedPreferences.Editor visibilityColorPreferencesEditor;

	public void initializeSharedPreferences(Context mContext){
		visibilityColorPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
		visibilityColorPreferencesEditor = visibilityColorPreferences.edit();
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	class Runner implements Runnable {

		@Override
		public void run() {
			while (!Thread.currentThread().isInterrupted()) {
				try{
					reminderThread.run();
					Thread.sleep(1000);
				}
				catch(Exception e){
					e.printStackTrace();
				}
			}
		}
	}

	//A thread that continuosly checks if the time reaches a reminder.
	Runnable reminderThread = new Runnable() {
		public void run() {
			Calendar c = Calendar.getInstance();
			currentHour = c.get(Calendar.HOUR_OF_DAY);
			currentMinute = c.get(Calendar.MINUTE);
			//Fire a notification
			Event event;
			if(!visibilityColorPreferences.getBoolean(MyHelper.SILENTMODE, false)){
				if((event = isItTime(currentHour, currentMinute)) != null){
					notification(event);

					//clear the reminder after notification is thrown!
					allEvents.get(event.getId()).setReminder(0); 

					//Update the database to set the reminder of the event to 0.
					allEvents.get(event.getId()).setReminder(0);
					datasource.open();
					datasource.updateEventReminder(event, 0);
					datasource.close();
				}
			}
		}
	};

	public Event isItTime(int hour, int minute){
		try{
			for (int i : allEventsIndices ) {
				Event event = allEvents.get(i);
				if(event.getBeginDate().equals(MyHelper.getTodaysDate())  && event.getReminder() > 0){ //Check if event's reminder is set and it's for today
					if(currentHour == event.getReminderHour() && currentMinute == event.getReminderMinute() ){
						return event;
					}
				}
			}
		}
		catch (Exception e){e.printStackTrace();}
		return null;

	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		mContext = this;
		initializeSharedPreferences(mContext);
		datasource = new TimeEditDataSource(mContext);
		Runner runner = new Runner();
		thread = new Thread(runner);
		if(!thread.isAlive()){
			thread.start();
		}
		initializeAllEvents();

		return START_NOT_STICKY;
	}

	//Refresh the events from database and add them to the local eventslist.
	public void initializeAllEvents(){
		allEvents = new SparseArray<Event>();
		allEventsIndices = new ArrayList<Integer>();
		allEvents.clear();
		allEventsIndices.clear();
		datasource.open();
		for(Event event : datasource.getAllEvents()){
			allEvents.put(event.getId(), event);
			allEventsIndices.add(event.getId());
		}
		datasource.close();
	}

	private void notification(Event event){
		Notification.Builder builder = new Notification.Builder(this);
		builder.setSmallIcon(android.R.drawable.ic_lock_idle_alarm)
		.setWhen(System.currentTimeMillis())
		.setAutoCancel(true);

		builder.setContentTitle(event.getCourse()+" in "+event.getReminder()+" minutes").setContentText("Click here to show the details.")
		.setContentInfo("Click!");
		long[] pattern = { 0, 400, 0, 400, -1 };
		builder.setVibrate(pattern);
		Intent intent = new Intent(this.getApplicationContext(), MyBroadcastReceiver.class);
		intent.setAction(MyBroadcastReceiver.ACTION);
		intent.putExtra(TimeEditDbHelper.COLUMN_ID, event.getId());
		intent.putExtra(TimeEditDbHelper.COLUMN_COURSE, event.getCourse());
		intent.putExtra(TimeEditDbHelper.COLUMN_ROOM, event.getRoom());
		intent.putExtra(TimeEditDbHelper.COLUMN_CITY, event.getCity());

		PendingIntent notifIntent = PendingIntent.getBroadcast(this, event.getId(), intent, Intent.FLAG_ACTIVITY_NEW_TASK);
		builder.setContentIntent(notifIntent);

		Notification notification = builder.build();
		Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
		notification.sound = soundUri;
		NotificationManager notifManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
		notifManager.notify(event.getId(), notification);

	}

	public void onDestroy() {
		System.out.println("Service Destroy!");
		super.onDestroy();
	}
}
